import { v4 } from "uuid";
import { ProxyBrowser, ProxyUser, useEntityManager, ProxyUserType } from "./entities";

export function loadBrowsers(type: ProxyUserType) {
    return useEntityManager(async m => {
        const qb = m.createQueryBuilder()
            .select(`"browser"."client_id"`, "client_id")
            .addSelect(`"user"."uid"`, "uid")
            .addSelect(`"user"."avatar"`, "avatar")
            .addSelect(`"user"."info"`, "info")
            .from(ProxyBrowser, 'browser')
            .leftJoinAndSelect(ProxyUser, 'user', '"user"."login_at"="browser"."client_id" and "user"."type"=:type', { type: type })

        return await qb.execute()
    })
}

export async function initBrowser() {
    const clientId = process.env.CLIENT_ID;
    await useEntityManager(async m => {
        const old = await m.findOne(ProxyBrowser, {where: {client_id: clientId}})
        const e = m.create(ProxyBrowser, {
            uuid: old?.uuid || v4(),
            client_id: clientId
        })
        await m.save(ProxyBrowser, e)
    })
}

